import * as constants from "./constants";
import { fromJS } from "immutable";

// fromJS返回一个 immutable 对象
const initialState = fromJS({
  focused: false,
  mouseIn: false,
  list: [],
  page: 1,
  pageSize: 5,
  pageTotal: 1,
});

const reducer = (state = initialState, action) => {
  const { type, payload } = action;
  switch (type) {
    // set 方法会结合之前的 immutable 对象的值和新设置的值，返回一个全新的对象
    case constants.SEARCH_FOCUS:
      return state.set('focused', true)
    case constants.SEARCH_BLUR:
      return state.set('focused', false)
    case constants.CHANGE_SEARCH_LIST:
      const list = payload.toJS();
      const pageSize = state.get('pageSize');
      const pageTotal = Math.ceil(list.length / pageSize);
      // return state.set('list', payload).set('pageTotal', pageTotal);
      return state.merge({
        list: payload,
        pageTotal
      })
    case constants.CHANGE_LIST_MOUSEIN:
      return state.set('mouseIn', true)
    case constants.CHANGE_LIST_MOUSEOUT:
      return state.set('mouseIn', false)
    case constants.CHANGE_LIST_PAGE:
      return state.set('page', payload)
    default:
      return state;
  }
}

export default reducer;